import {computed, ref} from 'vue';
import { message } from 'ant-design-vue';
import api from "@/utils/api";
import type {Capacity, CtrlPlan} from "./type.ts";

// 定义响应式变量
export const fetching = ref(false);
export const capacityList = ref<Capacity[]>([]);
export const capacitySearchList = ref<Capacity[]>([]);
export const newCapacityName = ref();

// 获取容量列表
export const fetchCapacities = async () => {
    try {
        fetching.value = true;
        const response = await api.get('/ctrlPlan/cpCapacity');
        capacityList.value = response.data;
    } catch (error) {
        message.error('获取容量列表失败');
        console.error('获取容量列表失败:', error);
    } finally {
        fetching.value = false;
    }
};

// 容量搜索
export const onCapacitySearch = async (cnDesc: string) => {
    if(capacityList.value===undefined || capacityList.value.length===0){
        await fetchCapacities();
    }
    if(capacityList.value){
        capacitySearchList.value = capacityList.value
            .filter(cp => cp.cnDesc.includes(cnDesc))
            .sort((a, b) => a.id - b.id);
    }
    if(cnDesc.length>0){
        newCapacityName.value = cnDesc;
    }
};

// 容量选择变化
export const onCapacityChange = (value: any,ctrlPlan:CtrlPlan) => {
    const cp= capacityList.value.find(cp =>
        cp.cnDesc === value
    );
    if (cp) {
        ctrlPlan.capacityId=cp.id;
        ctrlPlan.capacityCn=cp.cnDesc;
        newCapacityName.value=undefined;
    }
};

// 计算是否是新容量
export const isCapacityNew = computed(() => {
    return (newCapacityName && newCapacityName.value!==undefined)
})

// 容量失焦事件
export const onCapacityBlur = (ctrlPlan:CtrlPlan) => {
    if (isCapacityNew.value) {
        ctrlPlan.capacityId=undefined;
        ctrlPlan.capacityCn=newCapacityName.value;
        newCapacityName.value=undefined;
    }
};

export const createNewCapacity = async (cnDesc: string) => {
    if(cnDesc===undefined || cnDesc.length<1){
        return;
    }
    const oCapacity=capacityList.value.find(cp => cp.cnDesc===cnDesc)
    if(oCapacity && oCapacity.cnDesc===cnDesc){
        return;
    }
    try {
        fetching.value = true;

        await api.post('/ctrlPlan/cpCapacity', {
            cnDesc: cnDesc,
        });
        fetchCapacities();
        message.success(`新控制计划【${cnDesc}】创建成功`);
        return true;
    } catch (error) {
        message.error('创建控制计划失败');
        console.error('创建控制计划失败:', error);
        return false;
    } finally {
        fetching.value = false;
    }
};



// 重置容量数据
export const resetCapacityData = () => {
    capacityList.value = [];
};

// 导出所有方法
export default {
    capacityList,
    fetching,
    isCapacityNew,
    fetchCapacities,
    onCapacitySearch,
    onCapacityBlur,
    onCapacityChange,
    createNewCapacity,
    resetCapacityData
};